package com.main;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import com.entity.Order;
import com.entity.OrderItem;
import com.entity.Product;
import com.entity.Promotion;

public class Calculate {

	/**
	 * 计算总价格
	 * 
	 * @param order
	 * @return
	 */
	public static BigDecimal calculatePrice(Order order) {
		BigDecimal totalPrice = BigDecimal.ZERO;
		StringBuilder formular = new StringBuilder(); // 用于拼接公式
		List<OrderItem> orderItemList = order.getOrderItemList();
		for (OrderItem orderItem : orderItemList) {
			Product product = orderItem.getProduct();
			int quantity = orderItem.getQuantity();
			BigDecimal price = product.getPrice();

			BigDecimal itemTotalPrice = price.multiply(BigDecimal.valueOf(quantity));
			totalPrice = totalPrice.add(itemTotalPrice);

			formular.append("(").append(price).append(" * ").append(quantity).append(") + ");
		}

		if (formular.length() > 0) {
			formular.delete(formular.length() - 3, formular.length()); // 删除最后的 "+ "
		}

		List<Promotion> promotionList = order.getPromotionList();
		if (promotionList != null) {
			for (Promotion promotion : promotionList) {
				Date currentDate = new Date();
				// 判断是否限时活动并且在活动期间内
				if (promotion.getBeginDate() != null && promotion.getBeginDate().before(currentDate)) {
					continue;
				}
				if (promotion.getEndDate() != null && promotion.getEndDate().after(currentDate)) {
					continue;
				}
				// TODO 二次促销满减规则，是折前满一百 还是折后满一百也能算？
				order.setTotalPrice(totalPrice);
				BigDecimal discount = promotion.getDeductPrice(order);
				totalPrice = totalPrice.subtract(discount);

				formular.append(" - ").append(discount);
			}
		}
		formular.append("=").append(totalPrice.toPlainString());
		System.out.println("计算公式: " + formular.toString());

		return totalPrice;
	}

}
